<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 头部警告区域 -->
      <el-alert title="注意: 只允许为第三级分类设置相关参数!" type="warning" show-icon :closable="false">
      </el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类: </span>
          <!-- 级联选择菜单 -->
          <el-cascader v-model="selectedKey" :options="cateList" :props="optCates" @change="ParamshandleChange">
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tag区域 -->
      <el-tabs v-model="activeName" @tab-click="handleTblClick">
        <!--动态参数面板  -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addManyParams">
            添加参数
          </el-button>
          <!-- 列表数据 -->
          <el-table :data="manyParamsData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="closeTag(scope.row,i)">{{ item }}</el-tag>
                <!-- input输入框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加button按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 正常列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDilogVisible(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParamsByid(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态参数面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="addManyParams">
            添加属性
          </el-button>
          <!-- 数据列表 -->
          <el-table :data="onlyParamsData" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable v-for="(item, i) in scope.row.attr_vals" :key="i" @close="closeTag(scope.row,i)">
                  {{ item }}
                </el-tag>
                <!-- input输入框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)" @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 添加button按钮 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="editDilogVisible(scope.row.attr_id)">
                  编辑
                </el-button>
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeParamsByid(scope.row.attr_id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加动态参数对话框 -->
    <el-dialog :title="'添加' + titleText" :visible.sync="addParamdialogVisible" width="50%" @close="closeAddParam">
      <!-- 动态参数 -->
      <el-form :model="addParamruleForm" :rules="addParamrules" ref="addParamruleFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog :title="'修改' + titleText" :visible.sync="editParamdialogVisible" width="50%" @close="closeEditParam">
      <!-- 动态参数 -->
      <el-form :model="editParamruleForm" :rules="editParamrules" ref="editParamruleFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamruleForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品数据列表
      cateList: [],
      optCates: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 级联选择器双向绑定的数组
      selectedKey: [],
      // tag选择器默认选中的tag
      activeName: 'many',
      // 动态表格的参数
      manyParamsData: [],
      // 静态表格的参数
      onlyParamsData: [],
      // 添加动态参数对话框属性
      addParamdialogVisible: false,
      // 动态参数
      addParamruleForm: { attr_name: '', attr_sel: '' },
      // 动态参数校验规则
      addParamrules: {
        attr_name: {
          required: true,
          message: '参数不能为空请输入',
          trigger: 'blur',
        },
      },

      // 修改对对话框参数
      editParamruleForm: {},
      // 修改对话框规则
      editParamrules: {
        attr_name: {
          required: true,
          message: '参数不能为空请输入',
          trigger: 'blur',
        },
      },
      // 修改对话框展示的属性
      editParamdialogVisible: false,

      // 展开列最后一个添加文本框
      // inputVisible: false,
      // 展开列的文本输入框
      // inputValue: '',
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品数据列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      console.log(res)
      if (res.meta.status !== 200)
        return this.$message.error('获取商品列表失败!')
      this.cateList = res.data
    },
    // 级联选择框双击触发的函数
    async ParamshandleChange() {
      this.getParamsData()
    },
    // 获取参数
    async getParamsData() {
      console.log(this.selectedKey)
      // 级联选择器只能选第三级
      if (this.selectedKey.length !== 3) {
        this.selectedKey = []
        this.manyParamsData = []
        this.onlyParamsData = []
        return
      }

      const { data: res } = await this.$http.get(
        `categories/${this.CateId}/attributes`,
        {
          params: { sel: this.activeName },
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取参数失败')
      // 循环参数列表，并把attr_vals以逗号分隔，变成一个数组
      res.data.forEach((item) => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        // 文本框的值
        item.inputValue = ''
      })

      console.log(res.data)

      if (this.activeName === 'many') {
        this.manyParamsData = res.data
      } else {
        this.onlyParamsData = res.data
      }
    },
    // tag点击事件
    handleTblClick() {
      this.getParamsData()
      console.log(this.activeName)
    },

    // 添加动态参数对话框
    addManyParams() {
      this.addParamdialogVisible = true
    },
    // 关闭添加动态参数对话框
    closeAddParam() {
      this.$refs.addParamruleFormRef.resetFields()
    },
    // 当点击确认按钮 添加动态参数
    addParams() {
      // 先获取商品列表
      // 预先校验
      this.$refs.addParamruleFormRef.validate(async (valide) => {
        console.log(valide)
        if (!valide) return
        // 校验成功 发起添加参数请求
        const { data: res } = await this.$http.post(
          `categories/${this.CateId}/attributes`,
          {
            attr_name: this.addParamruleForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 201)
          return this.$message.error('创建动态参数失败')
        console.log(res)
        this.getParamsData()
        this.addParamdialogVisible = false
      })
    },

    // 修改参数对话框
    async editDilogVisible(attr_id) {
      this.editParamdialogVisible = true
      // 根据id获取参数信息
      const { data: res } = await this.$http.get(
        `categories/${this.CateId}/attributes/${attr_id}`
      )
      if (res.meta.status !== 200)
        return this.$message.error('查询参数列表失败')

      this.editParamruleForm = res.data
    },

    // 修改对话框确认按钮
    editParams() {
      // 点击确认进行预校验
      this.$refs.editParamruleFormRef.validate(async (valide) => {
        console.log(valide)
        if (!valide) return
        const { data: res } = await this.$http.put(
          `categories/${this.CateId}/attributes/${this.editParamruleForm.attr_id}`,
          {
            attr_name: this.editParamruleForm.attr_name,
            attr_sel: this.activeName,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.getParamsData()
        this.editParamdialogVisible = false
      })
    },

    // 关闭修改参数对话框
    closeEditParam() {
      this.$refs.editParamruleFormRef.resetFields()
    },

    // 删除按钮功能
    async removeParamsByid(attr_id) {
      const res = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      console.log(res)
      if (res !== 'confirm') return this.$message.info('取消了删除分类信息')
      const { data: resu } = await this.$http.delete(
        `categories/${this.CateId}/attributes/${attr_id}`
      )
      console.log(resu)
      if (resu.meta.status !== 200)
        return this.$message.error('删除分类信息失败')
      this.$message.success('删除分类信息成功')
      this.getParamsData()
    },
    // 展开列的最后一个按钮
    async handleInputConfirm(row) {
      // 如果输入的内容为空：清空掉
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false;
        return
      }
      // 如果没有清空 说明输入的值合法
      row.attr_vals.push(row.inputValue.trim())
      // row.inputValue = '';
      row.inputVisible = false;
      row.inputValue = ''
      // 发起请求 保存输入的数据
      this.saveAttrValus(row)

    },
    // 保存修改attr_vals的操作
    async saveAttrValus(row) {
      const { data: res } = await this.$http.put(`categories/${this.CateId}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })
      if (res.meta.status !== 200) return this.$message.error('修改参数失败')
      this.$message.success('修改参数成功')
    },

    // 展开列的文本输入框
    showInput(row) {
      row.inputVisible = true
      // 文本框自动获取焦点
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },


    // 删除tag标签
    closeTag(row, i) {
      console.log(row, i)
      row.attr_vals.splice(i, 1)
      // 发起请求 保存输入的数据
      this.saveAttrValus(row)
    }
  },

  computed: {
    // 如果需要被禁用返回true 否则返回fasle
    isBtnDisabled() {
      if (this.selectedKey.length !== 3) {
        return true
      } else {
        return false
      }
    },

    // 分类id
    CateId() {
      if (this.selectedKey.length === 3) {
        return this.selectedKey[2]
      }
      return null
    },

    // 动态添加对话框
    titleText() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态参数'
      }
    },
  },
}
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.input-new-tag {
  width: 150px;
}
</style>